#include "parser.h"

ParserPtr Parser::parser_ = nullptr;

ParserPtr Parser::getInst()
{
    if (!parser_)
    {
        parser_ = new Parser();
    }
    return parser_;
}

stringVecPtr Parser::parse(const Protocol &proto)
{
    return parseBuf(proto.buf_); 
}

// TODO: 将用户返回出去，可以更改tcp path
shared_ptr<User> Parser::verify(const Protocol &proto)
{
    if (proto.behavior_ == Behavior::LOGIN)
    {
        return doLogin(proto.buf_);
    }
    else if (proto.behavior_ == Behavior::REGISTER)
    {
        return doRegister(proto.buf_);
    }
    return nullptr;
}

shared_ptr<User> Parser::doLogin(const char *buf)
{
    stringVecPtr param = parseBuf(buf);

#ifdef DEBUG
    cout << "doLogin: " << buf << endl;
#endif

    shared_ptr<User> user = Mysql::queryUserByUnamePwd(param->at(0), param->at(1));
    return user;
}

// 用户注册
shared_ptr<User> Parser::doRegister(const char *buf)
{
    stringVecPtr param = parseBuf(buf);

#ifdef DEBUG
    cout << "doRegister: " << buf << endl;
#endif

    shared_ptr<User> user = Mysql::insert(param->at(0), param->at(1));
    return user;
}



stringVecPtr Parser::parseBuf(const char *buf)
{
    stringVecPtr params = std::make_shared<vector<string>>();
    string tmp;
    for (int i{}; buf[i] != '\0' && i < PROTOCOL_BUF_LEN; i++)
    {
        if (buf[i] == ' ' && tmp.size() > 0)
        {
            params->emplace_back(tmp);
            tmp.clear();
        }
        else
        {
            tmp += buf[i];
        }
    }
    if (tmp.size() > 0)
    {
        params->emplace_back(tmp);
    }
    return params;
}

Parser::Parser()
{}

Parser::~Parser()
{}